package org.example.netty.test.nio.util;

import org.example.netty.test.nio.netty.chat.bean.AbsMessageBase;
import org.example.netty.test.nio.netty.chat.service.UserService;
import org.example.netty.test.nio.netty.chat.util.FileUtil;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author zp
 * @version 1.0
 * @description: 接口工厂 根据接口返回实现类
 * @date 2023/5/30 19:20
 */
public class ServiceFactory {
    public static final String SERVICE_CONFIG = "/service.properties";

    private static Map<String, Object> getServiceImplMap(){
        Map<String, Object> serviceImplMap = new HashMap<>();
        InputStream inputStream = AbsMessageBase.class.getResourceAsStream(SERVICE_CONFIG);
        Properties properties = new Properties();
        try {
            properties.load(inputStream);
            Enumeration<?> enumeration = properties.propertyNames();
            while (enumeration.hasMoreElements()) {
                Object o = enumeration.nextElement();
                String property = properties.getProperty((String) o);
                serviceImplMap.put((String) o,Class.forName(property).newInstance());
            }
        } catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
        return serviceImplMap;
    }

    public static Object buildService(Class<?> classType){
        return  getServiceImplMap().get(classType.getName());
    }

    public static void main(String[] args) throws ClassNotFoundException {
        Class<?> aClass = Class.forName("org.example.netty.test.nio.netty.chat.service.UserService");
        System.out.println(buildService(aClass).getClass().getName());

    }
}
